import axios from "axios";
import router from "./router";
import Element from "element-ui";
import qs from "qs";
import store from "./store";
// axios.defaults.baseURL = "http://116.62.237.222/"
const request = axios.create({
  timeout: 5000,
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    Authorization: "Bearer " + localStorage.getItem("token"),
  },
  transformRequest: [
    function(data) {
      data = qs.stringify(data);
      return data;
    },
  ],
});
request.interceptors.request.use((config) => {
  if (store.state.token) {
    config.headers["Authorization"] = "Bearer " + localStorage.getItem("token");
  }
  return config;
});
request.interceptors.response.use(
  (response) => {
    let data = JSON.parse(JSON.stringify(response));
    let res = response.data;
    let url = data.config.url;
    console.log("response ->", data);
    if (url == "/oauth/token") {
      return res;
    } else {
      if (res.code === 200) {
        return res;
      } else {
        Element.Message.error(!res.msg ? "系统异常" : res.msg);
        return Promise.reject(res.msg);
      }
    }
  },
  (error) => {
    console.log(error);
    if (error.response.data) {
      error.massage = error.response.data.msg;
    }
    if (error.response.status === 401) {
      router.push("/login");
    }
    Element.Message.error(error.massage, { duration: 3000 });
    return Promise.reject(error);
  }
);
export default request;
